
#include "app_net.h"


static pthread_t	tcp_client_thread;

static int  socket_client 	  = -1;


void app_tcp_client_task(void *para)
{
	int one = 1;
	int ret = -1;
	int nNetTimeout=5000;

	int  data_len = 0;
	char recv_data[1024];
	char send_data[1024];
	
	struct sockaddr_in recv_addr;
	struct sockaddr_in serv_addr;

	char * ip = "192.168.3.3";

	if(!ip){
		return ;
	}

	log_d("ip=%s\n",ip);
 
	socket_client = socket(AF_INET, SOCK_STREAM, 0);
	if(socket_client < 0){
		log_d("socket error.\n");
		return ;
	}else{
		log_d("Socket succeed.\n");
	}
	
	if(setsockopt(socket_client, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0){
		close(socket_client);
		socket_client = -1;
		log_d("socket error.\n");
		return ;
	}
	//***************************************************************************************
	struct timeval timeout = {2,0};

	ret = setsockopt(socket_client,SOL_SOCKET,SO_SNDTIMEO,(struct timeval *)&timeout,sizeof(struct timeval));
	if(ret< 0){
		log_d("set socket timeout error,ret=%d\n",ret);
	}else{
		log_d("set succeed.\n");
	}

	ret = setsockopt(socket_client,SOL_SOCKET,SO_RCVTIMEO,(struct timeval *)&timeout,sizeof(struct timeval));
	if(ret< 0){
		log_d("set timeout socket timeout error,ret=%d\n",ret);
	}else{
		log_d("set timeout succeed.\n");
	}
	//***************************************************************************************

	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_family 	  = AF_INET;
	serv_addr.sin_port 		  = htons(CFG_LISTEN_PORT); 
	serv_addr.sin_addr.s_addr = inet_addr(ip);

	log_d("start connect server...\n");

	while(1)
	{
		usleep(100*1000);

		ret = connect(socket_client, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
		if(ret < 0){
			continue;
		}

		log_d("connect server succeed...\n");

		while(1)
		{
			usleep(1000);
			//**********************************************************
			memset(send_data,0,sizeof(send_data));

			sprintf(send_data,"%s","tcp client send.");

			data_len = strlen(send_data);
			ret = write(socket_client, send_data,data_len);
			if(ret != data_len){
				log_d("write error...\n");
			}
			//**********************************************************
			memset(recv_data,0,sizeof(recv_data));

			ret = read(socket_client,recv_data,sizeof(recv_data));
			if(ret <= 0){
				continue;
			}
			
			log_d("recv_data=%d:%s\n",ret,recv_data);
			//**********************************************************

		}
	}

	log_d("socket client close...\n");

	close(socket_client);
	socket_client = -1;


	return ;

}


int app_client_create(void)
{
	int ret = -1;
	
	ret=pthread_create(&tcp_client_thread, NULL, app_tcp_client_task, NULL);
	if(ret != 0){
		log_e("error=%s\n",strerror(ret));
	}

	return 0;
}





